<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<u-navbar title="我的订单" :autoBack="true"></u-navbar>
		
		<!-- 订单状态选项卡 -->
		<view class="order-tabs">
			<view class="tab-item" 
				v-for="(tab, index) in tabs" 
				:key="index" 
				:class="{'active': currentTab === index}"
				@click="switchTab(index)">
				<text>{{tab}}</text>
				<view class="tab-line" v-if="currentTab === index"></view>
			</view>
		</view>
		
		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-list" @scrolltolower="loadMore" refresher-enabled
			:refresher-triggered="refreshing" @refresherrefresh="onRefresh">
			<view v-if="orderList.length > 0">
				<view class="order-item" v-for="(order, index) in orderList" :key="index" @click="goToOrderDetail(order)">
					<view class="order-header">
						<view class="order-number">订单号：{{order.order_number}}</view>
						<view class="order-status" :class="'status-' + order.order_status">{{getStatusText(order.order_status)}}</view>
					</view>
					
					<view class="product-list">
						<view class="product-item" v-for="(product, pIndex) in order.products" :key="pIndex">
							<image class="product-image" :src="product.thumbnail" mode="aspectFill"></image>
							<view class="product-info">
								<view class="product-name">{{product.name}}</view>
								<view class="product-price-quantity">
									<text class="product-price" v-if="product.payment_type === 0">¥{{product.price}}</text>
									<text class="product-price" v-else-if="product.payment_type === 1">{{product.points_price}}积分</text>
									<text class="product-price" v-else>¥{{product.price}} + {{product.points_price}}积分</text>
									<text class="product-quantity">x{{product.quantity}}</text>
								</view>
							</view>
						</view>
					</view>
					
					<view class="order-footer">
						<view class="order-total">
							<text>共{{getTotalQuantity(order)}}件商品</text>
							<text class="total-amount">合计：¥{{(order.total_price + order.shipping).toFixed(2)}}</text>
							<text class="total-points" v-if="order.total_points > 0">+ {{order.total_points}}积分</text>
						</view>
						
						<view class="order-actions">
							<view class="action-btn cancel" v-if="order.order_status === 0" @click.stop="cancelOrder(order)">取消订单</view>
							<view class="action-btn primary" v-if="order.order_status === 0" @click.stop="goToPay(order)">去支付</view>
							<view class="action-btn primary" v-if="order.order_status === 1" @click.stop="remindShipping(order)">提醒发货</view>
							<view class="action-btn primary" v-if="order.order_status === 2" @click.stop="confirmReceive(order)">确认收货</view>
							<view class="action-btn primary" v-if="order.order_status === 3" @click.stop="goToComment(order)">去评价</view>
							<view class="action-btn normal" v-if="order.order_status >= 3" @click.stop="buyAgain(order)">再次购买</view>
						</view>
					</view>
				</view>
				
				<!-- 加载更多 -->
				<view class="load-more" v-if="hasMore">
					<u-loadmore :status="loadMoreStatus" />
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-else class="empty-state">
				<image src="/static/images/empty_order.png"  class="empty-image"></image>
				<text class="empty-text">暂无订单</text>
				<view class="go-shopping-btn" @click="goShopping">去购物</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabs: ['全部', '待付款', '待发货', '待收货', '已完成'],
				currentTab: 0,
				orderList: [],
				allOrders: [],
				page: 1,
				pageSize: 10,
				hasMore: false,
				loadMoreStatus: 'loadmore', // loadmore, loading, nomore
				refreshing: false
			}
		},
		onLoad(options) {
			// 如果有传入状态参数，切换到对应选项卡
			if (options.status !== undefined) {
				this.currentTab = parseInt(options.status);
			}
			
			// 加载订单数据
			this.loadOrders();
		},
		methods: {
			// 加载订单数据
			loadOrders() {
				// 获取本地存储的订单数据
				this.allOrders = uni.getStorageSync('officeShopOrders') || [];
				
				// 根据当前选项卡筛选订单
				this.filterOrders();
			},
			
			// 根据选项卡筛选订单
			filterOrders() {
				if (this.currentTab === 0) {
					// 全部订单
					this.orderList = this.allOrders.slice(0, this.page * this.pageSize);
				} else {
					// 根据状态筛选
					const status = this.currentTab - 1;
					const filteredOrders = this.allOrders.filter(order => order.order_status === status);
					this.orderList = filteredOrders.slice(0, this.page * this.pageSize);
				}
				
				// 判断是否还有更多数据
				if (this.currentTab === 0) {
					this.hasMore = this.orderList.length < this.allOrders.length;
				} else {
					const status = this.currentTab - 1;
					const filteredOrders = this.allOrders.filter(order => order.order_status === status);
					this.hasMore = this.orderList.length < filteredOrders.length;
				}
				
				// 更新加载更多状态
				this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore';
			},
			
			// 切换选项卡
			switchTab(index) {
				if (this.currentTab === index) return;
				
				this.currentTab = index;
				this.page = 1;
				this.filterOrders();
			},
			
			// 加载更多
			loadMore() {
				if (!this.hasMore) return;
				
				this.loadMoreStatus = 'loading';
				
				// 模拟加载延迟
				setTimeout(() => {
					this.page++;
					this.filterOrders();
				}, 500);
			},
			
			// 下拉刷新
			onRefresh() {
				this.refreshing = true;
				
				// 重新加载订单数据
				setTimeout(() => {
					this.page = 1;
					this.loadOrders();
					this.refreshing = false;
				}, 1000);
			},
			
			// 获取订单状态文本
			getStatusText(status) {
				const statusMap = {
					0: '待付款',
					1: '待发货',
					2: '待收货',
					3: '已完成',
					4: '已取消'
				};
				
				return statusMap[status] || '未知状态';
			},
			
			// 获取订单商品总数量
			getTotalQuantity(order) {
				return order.products.reduce((total, product) => total + product.quantity, 0);
			},
			
			// 跳转到订单详情
			goToOrderDetail(order) {
				uni.navigateTo({
					url: `/pages/order/detail?order_number=${order.order_number}`
				});
			},
			
			// 取消订单
			cancelOrder(order) {
				uni.showModal({
					title: '取消订单',
					content: '确定要取消该订单吗？',
					success: (res) => {
						if (res.confirm) {
							// 更新订单状态
							this.updateOrderStatus(order.order_number, 4); // 4: 已取消
							
							uni.showToast({
								title: '订单已取消',
								icon: 'success'
							});
							
							// 重新加载订单数据
							this.loadOrders();
						}
					}
				});
			},
			
			// 去支付
			goToPay(order) {
				uni.navigateTo({
					url: `/pages/order/payment?order_number=${order.order_number}`
				});
			},
			
			// 提醒发货
			remindShipping(order) {
				uni.showToast({
					title: '已提醒商家发货',
					icon: 'success'
				});
			},
			
			// 确认收货
			confirmReceive(order) {
				uni.showModal({
					title: '确认收货',
					content: '确认已收到商品吗？',
					success: (res) => {
						if (res.confirm) {
							// 更新订单状态
							this.updateOrderStatus(order.order_number, 3); // 3: 已完成
							
							uni.showToast({
								title: '确认收货成功',
								icon: 'success'
							});
							
							// 重新加载订单数据
							this.loadOrders();
						}
					}
				});
			},
			
			// 去评价
			goToComment(order) {
				uni.showToast({
					title: '评价功能开发中',
					icon: 'none'
				});
			},
			
			// 再次购买
			buyAgain(order) {
				// 将商品添加到购物车
				let cartList = uni.getStorageSync('officeShopCart') || [];
				
				order.products.forEach(item => {
					const cartItem = {
						id: item.id,
						name: item.name,
						thumbnail: item.thumbnail,
						price: item.price,
						points_price: item.points_price,
						quantity: item.quantity,
						payment_type: item.payment_type,
						selected: true,
						stock: item.stock || 999 // 如果没有库存信息，默认给一个较大的值
					};
					
					// 检查商品是否已在购物车中
					const existingIndex = cartList.findIndex(ci => ci.id === cartItem.id && ci.payment_type === cartItem.payment_type);
					
					if (existingIndex > -1) {
						// 更新数量
						cartList[existingIndex].quantity += cartItem.quantity;
					} else {
						// 添加新商品
						cartList.push(cartItem);
					}
				});
				
				// 保存购物车
				uni.setStorageSync('officeShopCart', cartList);
				
				// 跳转到购物车页面
				uni.switchTab({
					url: '/pages/cart/cart'
				});
			},
			
			// 更新订单状态
			updateOrderStatus(orderNumber, status) {
				const orderList = uni.getStorageSync('officeShopOrders') || [];
				const orderIndex = orderList.findIndex(item => item.order_number === orderNumber);
				
				if (orderIndex > -1) {
					orderList[orderIndex].order_status = status;
					
					// 根据状态设置相应的时间
					if (status === 3) {
						orderList[orderIndex].complete_time = new Date().getTime();
					} else if (status === 4) {
						orderList[orderIndex].cancel_time = new Date().getTime();
					}
					
					// 保存更新后的订单列表
					uni.setStorageSync('officeShopOrders', orderList);
					
					// 更新本地数据
					this.allOrders = orderList;
				}
			},
			
			// 去购物
			goShopping() {
				uni.switchTab({
					url: '/pages/officeShop/product/product'
				});
			}
		}
	}
</script>

<style lang="scss">
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f7fa;
}

.order-tabs {
	display: flex;
	background-color: #ffffff;
	border-bottom: 1px solid #f0f0f0;
	position: sticky;
	top: 0;
	z-index: 10;
}

.tab-item {
	flex: 1;
	height: 80rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
	font-size: 28rpx;
	color: #666;
	
	&.active {
		color: #007aff;
		font-weight: bold;
	}
	
	.tab-line {
		position: absolute;
		bottom: 0;
		width: 60rpx;
		height: 4rpx;
		background-color: #007aff;
		border-radius: 2rpx;
	}
}

.order-list {
	flex: 1;
	padding: 20rpx;
}

.order-item {
	background-color: #ffffff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.order-header {
	display: flex;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	border-bottom: 1px solid #f5f5f5;
}

.order-number {
	font-size: 26rpx;
	color: #666;
}

.order-status {
	font-size: 26rpx;
	font-weight: bold;
	
	&.status-0 {
		color: #ff9500; // 待付款
	}
	
	&.status-1 {
		color: #007aff; // 待发货
	}
	
	&.status-2 {
		color: #4cd964; // 待收货
	}
	
	&.status-3 {
		color: #8e8e93; // 已完成
	}
	
	&.status-4 {
		color: #8e8e93; // 已取消
	}
}

.product-list {
	padding: 20rpx 30rpx;
}

.product-item {
	display: flex;
	margin-bottom: 20rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.product-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 26rpx;
	color: #333;
	margin-bottom: 10rpx;
	// 最多显示两行
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.product-price-quantity {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.product-price {
	color: #ff5500;
	font-size: 26rpx;
}

.product-quantity {
	color: #999;
	font-size: 26rpx;
}

.order-footer {
	padding: 20rpx 30rpx;
	border-top: 1px solid #f5f5f5;
}

.order-total {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	margin-bottom: 20rpx;
	font-size: 26rpx;
	color: #666;
}

.total-amount {
	margin-left: 20rpx;
	color: #333;
	font-weight: bold;
}

.total-points {
	color: #ff9500;
	margin-left: 10rpx;
}

.order-actions {
	display: flex;
	justify-content: flex-end;
}

.action-btn {
	padding: 10rpx 20rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
	margin-left: 20rpx;
	
	&.normal {
		background-color: #f5f5f5;
		color: #666;
	}
	
	&.primary {
		background-color: #007aff;
		color: #ffffff;
	}
	
	&.cancel {
		border: 1px solid #999;
		color: #666;
	}
}

.load-more {
	padding: 20rpx 0;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 40rpx;
}

.go-shopping-btn {
	background-color: #007aff;
	color: #ffffff;
	padding: 20rpx 60rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
}
</style>
